import preferences from '@ohos.data.preferences';
import defaultAppManager from '@ohos.bundle.defaultAppManager';



class PreferenceUtil{
  prefMap:Map<string,preferences.Preferences>=new Map();

  async loadPreference(context,name:string){
    // preferences.getPreferences(context,name)
    //   .then(pref=>{
    //     this.prefMap.set(name,pref)
    //     console.log('tesTag',`加载Preference[${name}]成功`)
    //   })
    //   .catch(reason=>{
    //     console.log('tesTag',`加载Preference[${name}]失败`,JSON.stringify(reason))
    //   })
    try{
      //加载prefenence
      let pref=await preferences.getPreferences(context,name)
      this.prefMap.set(name,pref)
      console.log('testTag',`加载Preference[${name}]成功`)
    }catch (e){
      console.log('testTag',`加载Preference[${name}]失败`,JSON.stringify(e))
    }
  }

  async putPreferenceValue(key:string,Value:preferences.ValueType,name:string) {
    if (!this.prefMap.has(name)) {
      console.log('testTag', `Preference[${name}]尚未初始化！`)
      return
    }
    try {
      let pref=this.prefMap.get(name)
      //写入数据
      await pref.put(key, Value)
      //刷盘
      await pref.flush()
      console.log( `保存Preference[${key} = ${Value}]成功`)
    } catch (e) {
      console.log( `保存Preference[${key}= ${Value}]失败`, JSON.stringify(e))
    }
  }


  async getPreferenceValue(name:string,key:string,defaultValue:preferences.ValueType){
    if(!this.prefMap.has(name)){
      console.log('testTag',`Preference[${name}]尚未初始化！`)
      return
    }
    try {

      let pref=this.prefMap.get(name)

      //读数据

      let value=await pref.get(key,defaultValue)
      console.log('testTag',`读取Preference[${key} = ${value}]成功`)
      return value
    }catch (e){
      console.log('tesTag',`读取Preference[${key}]失败`,JSON.stringify(e))
    }
  }

}

const preferenceUtil = new PreferenceUtil()

export default preferenceUtil as PreferenceUtil